package com.wanyang.controller;

import com.wanyang.pojo.User;
import com.wanyang.service.UserService;
import com.wanyang.util.ResponseData;
import com.wanyang.util.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * Created by zhai on 16/4/17.
 */
@Controller
public class SystemController extends BaseController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String getLoginView(Model model, HttpSession session) {
        if(null != session.getAttribute("user")) {
            User user = (User) session.getAttribute("user");
            model.addAttribute("userId", user.getUserId());
            model.addAttribute("username", user.getUsername());
            return "server/pages/admin-index";
        }
        return "server/pages/admin-login";
    }

    @RequestMapping(value = "/userLogin")
    @ResponseBody
    public Object userLogin(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) {
        ResponseData responseData = new ResponseData();
        User user = userService.login(username, password);
        if (null != user) {
            responseData.setStatus(Status.success);
            responseData.setData(user.getUserId());
            session.setAttribute("user", user);
        } else {
            responseData.setStatus(Status.error);
        }
        return responseData;
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String getIndexView(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if(null == user) {
            return "server/pages/admin-login";
        }
        model.addAttribute("userId", user.getUserId());
        model.addAttribute("username", user.getUsername());
        return "server/pages/admin-index";
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(Model model, HttpSession session) {
        session.removeAttribute("user");
        return "server/pages/admin-login";
    }
}
